/*
 * 本类负责服务器端的数据返回
 * 2011-11-07:completed initially by gongshw
 */
package nju.mscs.data;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import nju.mscs.data.object.Database;
import nju.mscs.data.object.GiftList;
import nju.mscs.data.object.Inventory;
import nju.mscs.data.object.PromotionList;
import nju.mscs.data.object.SaleRecord;
import nju.mscs.data.object.UserList;
import nju.mscs.data.object.VipList;
import nju.mscs.data.object.VipUpdataList;
import nju.mscs.server.businessLogic.Controller;

public class NetServerManager extends NetManager{
	
	private List<Database> databaseList; 
	private Check ch;
	public NetServerManager(List<Database> database){
		this.databaseList = database;
		ch=new Check(Controller.sumDB);
	}
	
	public void startDownloadServer(int port) throws IOException{
		ServerSocket ss = setServer(port);
		while(true){
			final Socket  socket = ss.accept();
			new Thread(new Runnable(){

				@Override
				public void run() {
					try {
						handleDownloadSocket(socket);
					} catch (IOException e) {
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}}).start();
		}
	}
	public void startUploadServer(int port) throws IOException{
		ServerSocket ss = setServer(port);
		while(true){
			final Socket  socket = ss.accept();
			new Thread(new Runnable(){

				@Override
				public void run() {
					try {
						handleUploadSocket(socket);
					} catch (IOException e) {
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}}).start();
		}
	}
	
	public Iterator<Database> getUploadDatabase(){
		return databaseList.iterator();
	}
	
	
	private void handleUploadSocket(Socket socket) throws IOException, ClassNotFoundException{
		Database db = (Database) this.readFromSocket(socket);
		synchronized(databaseList){//网络线程
		databaseList.remove(getDatabaseById(db.getShopId()));
		
		databaseList.add(db);
		}
		ch.trim(db);//整合
		
	}

	private void handleDownloadSocket(Socket socket) throws IOException, ClassNotFoundException{
		
		String str = (String) this.readFromSocket(socket);
		Database db=getDatabaseById(str);
		if(db==null){
			Database DB=ch.copyDBFromSum();
			DB.setShopId(str);
			synchronized(databaseList){//网络线程
			databaseList.add(DB);//要改写配置文件中的size +1；
			System.out.println("ASAS:"+databaseList.size());
			}
		}
		//若没有，根据分店号添加一个新的Database
		this.writeToSocket(db, socket);
	}
	private Database getDatabaseById(String id){
		for(Database db:this.databaseList)
			if(db.getShopId().equals(id))
				return db;
		return null;
	}
}